<template>
  <div class="chat-container">
    <!-- 导航栏 -->
    <div class="nav-bar">
      <div class="back-button">
        <div class="circle-button" @click="back">
          <span class="arrow-left">←</span>
        </div>
      </div>
      <div class="tabs">
        <div class="tab" :class="{ active: activeTab === 'chat' }" @click="switchTab('chat')">对话</div>
        <div class="tab" :class="{ active: activeTab === 'profile' }" @click="switchTab('profile')">资料</div>
        <div class="tab-indicator" :style="{ left: activeTab === 'chat' ? '0' : '50%' }"></div>
      </div>
      <div class="more-button">
        <div class="circle-button">
          <span class="dots">•••</span>
        </div>
      </div>
    </div>

    <!-- 聊天内容 -->
    <div v-if="activeTab === 'chat'" class="chat-content">
      <div v-if="isLoading" class="loading-state">
        <div class="loading-spinner"></div>
        <div class="loading-text">加载中...</div>
      </div>
      <div v-else-if="hasError" class="error-state">
        <div class="error-icon">⚠️</div>
        <div class="error-text">加载失败，请稍后重试</div>
        <button class="retry-button" @click="fetchChatHistory">重试</button>
      </div>
      <template v-else>
        <div class="timestamp">11:21</div>

        <!-- 消息列表 -->
        <div v-for="message in messageStore.messages" :key="message.id"
          :class="['message-wrapper', message.senderId === currentUserId ? 'sent' : 'received']">
          <div class="avatar">
            <img
              :src="message.senderId === currentUserId ?
                'https://hebbkx1anhila5yf.public.blob.vercel-storage.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250329112213.jpg-xYCWJrQqTW8b4SD8u26nYOh9Ve7MRP.jpeg' :
                'https://hebbkx1anhila5yf.public.blob.vercel-storage.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250329112213.jpg-xYCWJrQqTW8b4SD8u26nYOh9Ve7MRP.jpeg'"
              alt="头像" class="avatar-img" />
          </div>
          <div class="message-bubble">
            <template v-if="message.type === 'text'">
              <div class="message-text">{{ message.content }}</div>
            </template>
            <template v-else-if="message.type === 'voice'">
              <div class="voice-message" @click="playVoice(message)">
                <div class="voice-icon" :class="{ 'playing': isPlaying === message.id }">
                  <span class="voice-wave"></span>
                  <span class="voice-wave"></span>
                  <span class="voice-wave"></span>
                </div>
                <div class="voice-duration">{{ message.duration }}''</div>
              </div>
            </template>
            <template v-else-if="message.type === 'emoji'">
              <div class="emoji-message">{{ message.content }}</div>
            </template>
          </div>
        </div>

        <!-- 个人资料卡片 -->
        <div class="profile-card" @click="switchTab('profile')">
          <div class="profile-card-inner">
            <div class="avatar">
              <img
                src="https://hebbkx1anhila5yf.public.blob.vercel-storage.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250329112213.jpg-xYCWJrQqTW8b4SD8u26nYOh9Ve7MRP.jpeg"
                alt="头像" class="avatar-img" />
            </div>
            <div class="profile-info">
              <div class="profile-name">九月</div>
              <div class="profile-link">她的整体资料 ></div>
            </div>
          </div>
        </div>

        <!-- 提示文本 -->
        <div class="hint-text">修改打招呼时发出的招呼语</div>

        <!-- 安全提醒 -->
        <div class="security-alert">
          <div class="security-header">
            <div class="security-icon">🛡️</div>
            <div class="security-title">安全提醒</div>
            <div class="security-link">常见诈骗方式</div>
          </div>
          <div class="security-content">
            <p>1.交流过程中，谨慎与他人交换联系方式。</p>
            <p>2.任何引导你产生钱财往来的行为都可能是诈骗，务必警惕！</p>
            <p>3.珍爱专注婚恋服务，不提供任何投资理财金融类服务，也不鼓励用户间存有该类行为。</p>
            <p>4.若发现疑似诈骗等不良行为的，请保护好自身人身财产安全并积极举报！</p>
          </div>
        </div>
      </template>
    </div>

    <!-- 资料内容 -->
    <div v-else class="profile-content">
      <ProfileTab :userId="currentUserId" :receiverId="receiverId" />
    </div>

    <!-- 输入框区域 -->
    <div class="input-area">
      <div class="voice-button" @mousedown="startVoiceRecording" @mouseup="stopVoiceRecording"
        @mouseleave="stopVoiceRecording">
        <div class="mic-icon">🎤</div>
        <div v-if="isRecording" class="recording-duration">
          {{ recordingDuration }}s
        </div>
      </div>
      <div class="text-input">
        <input type="text" v-model="inputText" @keyup.enter="sendMessage" placeholder="请输入内容..." />
      </div>
      <div class="emoji-button" @click="toggleEmojiPicker">
        <div class="emoji-icon">😊</div>
      </div>
    </div>

    <!-- 表情选择器 -->
    <div v-if="showEmojiPicker" class="emoji-picker" @click.stop>
      <div class="emoji-header">
        <div class="emoji-title">选择表情</div>
        <div class="emoji-close" @click="showEmojiPicker = false">×</div>
      </div>
      <div class="emoji-grid">
        <div v-for="emoji in messageStore.emojiList" :key="emoji" class="emoji-item" @click="sendEmoji(emoji)">
          {{ emoji }}
        </div>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div class="bottom-toolbar">
      <div class="tool-item">
        <div class="tool-icon">❓</div>
      </div>
      <div class="tool-item">
        <div class="tool-icon">🎁</div>
      </div>
      <div class="tool-item">
        <div class="tool-icon">•••</div>
      </div>
    </div>

    <!-- 底部指示条 -->
    <div class="bottom-indicator"></div>

    <!-- 提示信息 -->
    <div v-if="showToast" class="toast-message">
      {{ toastMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed,watch} from 'vue'
import { useMessageStore } from '@/stores/message'
import ProfileTab from './ProfileTab.vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const messageStore = useMessageStore()
const inputText = ref('')
const showEmojiPicker = ref(false)
const mediaRecorder = ref(null)
const audioChunks = ref([])
const activeTab = ref('chat')
const currentUserId = JSON.parse(localStorage.getItem('userInfo')).id
const isRecording = ref(false)
const recordingStartTime = ref(null)
const recordingDuration = ref(0)
const showToast = ref(false)
const toastMessage = ref('')
const isLoading = ref(false)
const hasError = ref(false)
const receiverId = computed(() => route.query.receiverId)
const isPlaying = ref(null)
const isFullscreen = ref(false)
const currentMedia = ref(null)
const fullscreenMediaRef = ref(null)

// 切换标签页
const switchTab = (tab) => {
  activeTab.value = tab
}

// 显示提示信息
const showMessage = (message) => {
  toastMessage.value = message
  showToast.value = true
  setTimeout(() => {
    showToast.value = false
  }, 2000)
}
const back = () => {
  router.push("/message")
}


// 发送文本消息
const sendMessage = async () => {
  const data = { 'receiverId': receiverId, 'content': inputText.value }

  if (!inputText.value.trim()) return
  try {
    const response = await messageStore.sendTextMessage(data)
    // 发送成功后立即添加消息到聊天记录
    messageStore.messages.push({
      id: Date.now(),
      type: 'text',
      content: inputText.value,
      senderId: 'currentUser',
      timestamp: new Date().toISOString()
    })
    // 清空输入框
    inputText.value = ''
  } catch (error) {
    console.error('发送消息失败:', error)
    showMessage('发送消息失败，请稍后重试')
  }
}

// 开始录音
const startVoiceRecording = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    mediaRecorder.value = new MediaRecorder(stream)
    audioChunks.value = []
    recordingStartTime.value = Date.now()

    mediaRecorder.value.ondataavailable = (event) => {
      audioChunks.value.push(event.data)
    }

    mediaRecorder.value.onstop = async () => {
      const audioBlob = new Blob(audioChunks.value, { type: 'audio/wav' })
      const duration = Math.floor((Date.now() - recordingStartTime.value) / 1000)
      try {
        const formData = { 'senderId': currentUserId, 'receiverId': receiverId, 'voiceFile': audioBlob, 'duration': duration }

        console.log(formData)
        await messageStore.sendVoiceMessage(formData)
        // 发送成功后立即添加消息到聊天记录
        messageStore.messages.push({
          type: 'voice',
          content: URL.createObjectURL(audioBlob),
          senderId: currentUserId,
          receiverId: receiverId,
          duration: duration,
          timestamp: new Date().toISOString()
        })
      } catch (error) {
        console.error('发送语音消息失败:', error)
        showMessage('发送语音消息失败，请稍后重试')
      }
      recordingDuration.value = 0
    }

    mediaRecorder.value.start()
    messageStore.startRecording()
    isRecording.value = true

    // 更新录音时长
    const timer = setInterval(() => {
      if (isRecording.value) {
        recordingDuration.value = Math.floor((Date.now() - recordingStartTime.value) / 1000)
      }
    }, 1000)
  } catch (error) {
    console.error('访问麦克风失败:', error)
    showMessage('无法访问麦克风，请检查权限设置')
  }
}

// 停止录音
const stopVoiceRecording = () => {
  if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
    mediaRecorder.value.stop()
    messageStore.stopRecording()
    isRecording.value = false
  }
}

// 发送表情
const sendEmoji = async (emoji) => {
  const data = {
    'receiverId': receiverId,
    'content': emoji,
    'senderId': currentUserId
  }
  try {
    const response = await messageStore.sendEmoji(data)
    // 发送成功后立即添加消息到聊天记录
    messageStore.messages.push({
      type: 'emoji',
      content: emoji,
      senderId: currentUserId,
      receiverId: receiverId,
      timestamp: new Date().toISOString()
    })
    showEmojiPicker.value = false
  } catch (error) {
    console.error('发送表情失败:', error)
    showMessage('发送表情失败，请稍后重试')
  }
}

// 切换表情选择器显示状态
const toggleEmojiPicker = () => {
  showEmojiPicker.value = !showEmojiPicker.value
}

// 点击其他地方关闭表情选择器
const closeEmojiPicker = (event) => {
  if (!event.target.closest('.emoji-picker') && !event.target.closest('.emoji-button')) {
    showEmojiPicker.value = false
  }
}

// 返回消息列表
const goBack = () => {
  router.push('/message')
}

// 获取聊天记录
const fetchChatHistory = async () => {
  isLoading.value = true
  try {
    const data = {
      userId2: receiverId.value,
      userId1: currentUserId
    }
    console.log(data)
    await Promise.all([
      messageStore.getChatHistory(data),
      messageStore.markAsRead(data)
    ])
  } catch (error) {
    console.error('获取聊天记录失败:', error)
    hasError.value = true
    showMessage('获取聊天记录失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 播放语音
const playVoice = (message) => {
  isPlaying.value = message.id
}

// 生命周期钩子
onMounted(async () => {
  //确保路由参数已解析
  router.isReady().then(() => {
    if (!receiverId.value) {
      console.error('未找到 receiverId 参数')
      router.push('/message')
    }
  })
  document.addEventListener('click', closeEmojiPicker)
})
watch(
  () => receiverId.value,
  (newVal) => {
    if (newVal) {
      console.log('[Debug] receiverId 变化:', newVal)

      fetchChatHistory()
    }
  },
  { immediate: true }
)

onUnmounted(() => {
  document.removeEventListener('click', closeEmojiPicker)
  if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
    stopVoiceRecording()
  }
})

const handleMediaClick = (item) => {
  currentMedia.value = item
  isFullscreen.value = true
}

const closeFullscreen = () => {
  isFullscreen.value = false
}

const isVideo = (item) => {
  return item.endsWith('.mp4') || item.endsWith('.mov') || item.endsWith('.avi')
}

const getVideoPoster = (item) => {
  // Logic to get video poster if needed
  return ''
}
</script>

<style scoped>
.chat-container {
  width: 100%;
  max-width: 414px;
  height: 100vh;
  margin: 0 auto;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

/* 状态栏样式 */
.status-bar {
  display: flex;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: #f5f5f5;
  font-weight: bold;
}

.time {
  font-size: 16px;
}

.status-icons {
  display: flex;
  gap: 8px;
}

/* 导航栏样式 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
}

.circle-button {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.arrow-left {
  font-size: 18px;
}

.dots {
  font-size: 18px;
  letter-spacing: 1px;
}

.tabs {
  display: flex;
  position: relative;
  background-color: #f0f0f0;
  border-radius: 20px;
  padding: 3px;
}

.tab {
  padding: 8px 30px;
  font-size: 16px;
  position: relative;
  z-index: 1;
  cursor: pointer;
  transition: color 0.3s;
}

.tab.active {
  color: #000;
  font-weight: bold;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 2px;
  width: 50%;
  background-color: #000;
  border-radius: 2px;
  transition: left 0.3s ease;
}

/* 聊天内容样式 */
.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px 15px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.timestamp {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin: 10px 0;
}

.profile-card {
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.profile-card:hover {
  background-color: #f8f8f8;
}

.profile-card-inner {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 5px;
  overflow: hidden;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.profile-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.profile-name {
  font-size: 16px;
  color: #666;
}

.profile-link {
  font-size: 14px;
  color: #333;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 15px;
}

.message-wrapper.sent {
  flex-direction: row-reverse;
}

.message-wrapper .avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.message-wrapper .avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-bubble {
  background-color: #fff;
  border-radius: 20px;
  padding: 10px 15px;
  max-width: 70%;
  display: flex;
  align-items: center;
  gap: 5px;
}

.message-wrapper.sent .message-bubble {
  background-color: #8e8ef1;
  color: white;
}

.message-wrapper.received .message-bubble {
  background-color: #fff;
}

.voice-message {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 60px;
  padding: 8px 12px;
  cursor: pointer;
  user-select: none;
}

.voice-icon {
  position: relative;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.voice-wave {
  width: 3px;
  height: 12px;
  background-color: currentColor;
  margin: 0 1px;
  border-radius: 1px;
  animation: wave 1s ease-in-out infinite;
}

.voice-wave:nth-child(2) {
  animation-delay: 0.2s;
}

.voice-wave:nth-child(3) {
  animation-delay: 0.4s;
}

.voice-icon.playing .voice-wave {
  animation: wave 0.5s ease-in-out infinite;
}

.voice-duration {
  font-size: 14px;
  color: inherit;
}

.message-wrapper.sent .voice-message {
  color: white;
}

.message-wrapper.received .voice-message {
  color: #333;
}

.emoji-message {
  font-size: 24px;
}

.emoji-picker {
  position: fixed;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #fff;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  width: 90%;
  max-width: 360px;
}

.emoji-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.emoji-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.emoji-close {
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0 5px;
}

.emoji-close:hover {
  color: #666;
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.emoji-item {
  font-size: 28px;
  text-align: center;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: background-color 0.2s;
}

.emoji-item:hover {
  background-color: #f5f5f5;
}

.hi-badge {
  background-color: #ff6b89;
  color: white;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
}

.message-text {
  font-size: 16px;
}

.hint-text {
  color: #8e8ef1;
  font-size: 14px;
  text-align: center;
}

.security-alert {
  background-color: #f0f0f0;
  border-radius: 10px;
  padding: 15px;
  margin-top: 20px;
}

.security-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.security-icon {
  font-size: 18px;
}

.security-title {
  font-size: 16px;
  font-weight: bold;
}

.security-link {
  color: #8e8ef1;
  font-size: 14px;
}

.security-content {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.security-content p {
  margin: 8px 0;
}

/* 输入框区域样式 */
.input-area {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f5f5;
  gap: 10px;
}

.voice-button,
.emoji-button {
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.text-input {
  flex: 1;
  background-color: #fff;
  border-radius: 20px;
  padding: 8px 15px;
}

.text-input input {
  width: 100%;
  border: none;
  outline: none;
  background: transparent;
  font-size: 16px;
}

/* 底部工具栏样式 */
.bottom-toolbar {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  border-top: 1px solid #eee;
}

.tool-item {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.bottom-indicator {
  width: 30%;
  height: 5px;
  background-color: #000;
  border-radius: 3px;
  margin: 5px auto;
}

.profile-content {
  flex: 1;
  overflow-y: auto;
  background-color: #f5f5f5;
}

.voice-button {
  position: relative;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f0f0;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease;
}

.voice-button:hover {
  background-color: #e0e0e0;
  transform: scale(1.05);
}

.voice-button:active {
  transform: scale(0.95);
  background-color: #d0d0d0;
}

.mic-icon {
  font-size: 20px;
  color: #666;
  transition: color 0.3s ease;
}

.voice-button:hover .mic-icon {
  color: #8e8ef1;
}

.recording-duration {
  position: absolute;
  top: -35px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  white-space: nowrap;
}

.recording-duration::after {
  content: '';
  position: absolute;
  bottom: -6px;
  left: 50%;
  transform: translateX(-50%);
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid rgba(0, 0, 0, 0.8);
}

/* 提示信息样式 */
.toast-message {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 9999;
  animation: fadeInOut 2s ease-in-out;
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
  }

  20% {
    opacity: 1;
  }

  80% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #8e8ef1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.loading-text {
  font-size: 14px;
}

.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #666;
  text-align: center;
  padding: 20px;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.error-text {
  font-size: 16px;
  margin-bottom: 20px;
}

.retry-button {
  padding: 8px 20px;
  background-color: #8e8ef1;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.retry-button:hover {
  background-color: #7a7ae0;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@keyframes wave {

  0%,
  100% {
    height: 6px;
  }

  50% {
    height: 12px;
  }
}

/* Add styles for fullscreen overlay */
.fullscreen-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.fullscreen-overlay img,
.fullscreen-overlay video {
  max-width: 90%;
  max-height: 90%;
}
</style>